package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuDiscountTo;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SpuBoundsTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.FeignCouponService;
import com.atguigu.gulimall.product.feign.FeignSearchService;
import com.atguigu.gulimall.product.feign.FeignWareService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    FeignCouponService feignCouponService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    FeignWareService feignWareService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //这里适合seata AT分布式事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuInfoVo spuInfoVo) {
        AtomicInteger sort = new AtomicInteger(0);
        //1、保存pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //2、保存pms_spu_info_desc
        List<String> decriptList = spuInfoVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decriptList));
        spuInfoDescService.save(spuInfoDescEntity);
        //3、保存pms_spu_images
        List<String> imagesList = spuInfoVo.getImages();
        List<SpuImagesEntity> spuImagesEntityList = imagesList.stream().map((images) -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(images);
            spuImagesEntity.setImgSort(sort.get());
            sort.getAndSet(sort.get() + 1);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        sort.set(0);
        spuImagesService.saveBatch(spuImagesEntityList);

        //4、保存gulimall_sms.sms_spu_bounds
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        Bounds bounds = spuInfoVo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        feignCouponService.spuBoundsSaveFeign(spuBoundsTo);

        //5、保存pms_product_attr_value
        List<BaseAttrs> baseAttrsList = spuInfoVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrsList.stream().map((baseAttrs) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(baseAttrs.getAttrId());
            AttrEntity attrEntity = attrService.getById(baseAttrs.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(baseAttrs.getAttrValues());
            productAttrValueEntity.setAttrSort(sort.get());
            sort.getAndSet(sort.get() + 1);
            productAttrValueEntity.setQuickShow(baseAttrs.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        sort.set(0);
        productAttrValueService.saveBatch(productAttrValueEntityList);

        //6、保存skus []
        List<Skus> skus = spuInfoVo.getSkus();
        skus.forEach((sku) -> {
            //6.1保存pms_sku_info
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            List<Images> skuImagesList = sku.getImages();
            List<Images> skuImagesDefaultList = skuImagesList.stream().filter(skuImages -> skuImages.getDefaultImg() == 1).collect(Collectors.toList());
            if (skuImagesDefaultList != null && skuImagesDefaultList.size() > 0) {
                skuInfoEntity.setSkuDefaultImg(skuImagesDefaultList.get(0).getImgUrl());
            }
            skuInfoService.save(skuInfoEntity);
            //6.2保存pms_sku_images
            List<SkuImagesEntity> skuImagesEntityList = skuImagesList.stream().filter(skuImages -> !skuImages.getImgUrl().equals("")).map((skuImages) -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                skuImagesEntity.setImgUrl(skuImages.getImgUrl());
                skuImagesEntity.setImgSort(sort.get());
                sort.getAndSet(sort.get() + 1);
                skuImagesEntity.setDefaultImg(skuImages.getDefaultImg());

                return skuImagesEntity;
            }).collect(Collectors.toList());
            sort.set(0);
            skuImagesService.saveBatch(skuImagesEntityList);
            //6.3保存pms_sku_sale_attr_value
            List<Attr> attrList = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrList.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                skuSaleAttrValueEntity.setAttrSort(sort.get());
                sort.getAndSet(sort.get() + 1);
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            sort.set(0);
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
            //6.4保存gulimall_sms.sms_member_price,gulimall_sms.sms_sku_full_reduction,gulimall_sms.sms_sku_ladder
            SkuDiscountTo skuDiscountTo = new SkuDiscountTo();
            BeanUtils.copyProperties(sku, skuDiscountTo);
            skuDiscountTo.setSkuId(skuInfoEntity.getSkuId());
            feignCouponService.discountSave(skuDiscountTo);
        });
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        /*
        status:
        key:
        brandId: 0
        catelogId: 0
        * */
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.lambda().eq(SpuInfoEntity::getPublishStatus, status);
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)) {
            queryWrapper.lambda().and((wrapper) -> {
                wrapper.eq(SpuInfoEntity::getId, key)
                        .or().like(SpuInfoEntity::getSpuName, key);
            });
        }


        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotBlank(brandId)) {
            if (Long.parseLong(brandId) != 0) {
                queryWrapper.lambda().eq(SpuInfoEntity::getBrandId, brandId);
            }
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotBlank(catelogId)) {
            if (Long.parseLong(catelogId) != 0) {
                queryWrapper.lambda().eq(SpuInfoEntity::getCatalogId, catelogId);
            }
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Autowired
    FeignSearchService feignSearchService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void up(Long spuId) {
        //查询当前spu的所有可以被用来检索的规格属性 开始
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIdList = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIdList = attrService.selectSearchAttrs(attrIdList);
        Set<Long> idSet = new HashSet<>(searchAttrIdList);

        List<SkuEsModel.Attrs> searchedSpuAttrs = baseAttrs.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                }).collect(Collectors.toList());

        //查询当前spu的所有可以被用来检索的规格属性 结束

        //查出当前spuId对应的所有sku信息
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIdList = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skusHasStockR = feignWareService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> listTypeReference = new TypeReference<List<SkuHasStockVo>>(){};
            List<SkuHasStockVo> skusHasStock = skusHasStockR.getData(listTypeReference);
            stockMap = skusHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }


        //封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skuInfoEntityList.stream().map(skuInfoEntity -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, esModel);
            esModel.setSkuPrice(skuInfoEntity.getPrice());
            esModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }
            //TOTO 2、热度评分.默认给0
            esModel.setHostScore(0L);

            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            esModel.setAttrs(searchedSpuAttrs);

            return esModel;
        }).collect(Collectors.toList());

        //将数据发送给es进行保存
        R r = feignSearchService.productStatusUp(upProducts);
        if (r.getCode() == 0) {
            //远程调用成功
            //修改当前spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.UP_SPU.getCode());
        } else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性，重试机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = this.getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }
}